package com.cskaoyan.market.service;

import com.cskaoyan.market.bo.OrderDetailBo;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.MarketCommentMapper;
import com.cskaoyan.market.db.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.market.db.mapper.MarketOrderMapper;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.vo.Express;
import com.cskaoyan.market.vo.MarketOrderVo;
import com.cskaoyan.market.vo.MarketOrderVoColumns;
import com.cskaoyan.market.vo.TimeConUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Service
public class MarketOrderServiceImpl implements MarketOrderService {
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    short orderStatusArray = 0;
    int page = 0;
    int limit = 0;
    int userId = 0;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime startTime = null;
    LocalDateTime endTime = null;

    @Override
    public List<MarketOrder> list(String pageInput, String limitInput, String sort, String order, String orderStatusArrayInput, String startInput, String endInput, String userIdInput,String orderSn) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        marketOrderExample.setOrderByClause(sort+" "+order);
        try {
            page = Integer.parseInt(pageInput);
            limit = Integer.parseInt(limitInput);
        }catch (NumberFormatException e) {
            System.out.println("输入格式错误");
            return null;
        }

        if(!StringUtils.isEmpty(orderStatusArrayInput)){
            try {
                orderStatusArray = Short.parseShort(orderStatusArrayInput);
                criteria.andOrderStatusEqualTo(orderStatusArray);
            }catch (NumberFormatException e) {
                System.out.println("输入格式错误");
                return null;
            }
        }
        if(!StringUtils.isEmpty(userIdInput)){
            try {
                userId = Integer.parseInt(userIdInput);
                criteria.andUserIdEqualTo(userId);
            }catch (NumberFormatException e) {
                System.out.println("输入格式错误");
                return null;
            }
        }
        if(!StringUtils.isEmpty(startInput)&&!StringUtils.isEmpty(endInput)){
            criteria.andAddTimeBetween(startTime, endTime);
        }

        if(!StringUtils.isEmpty(orderSn)){
            criteria.andOrderSnEqualTo(orderSn);
        }
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        return marketOrders;
    }

    @Override
    public OrderDetailBo detail(int id) {
        OrderDetailBo orderDetailBo=new OrderDetailBo();
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(id);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(marketOrderExample);
        orderDetailBo.setOrder(marketOrder);


        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria marketOrderGoodsCriteria = marketOrderGoodsExample.createCriteria();
        marketOrderGoodsCriteria.andOrderIdEqualTo(marketOrder.getId());
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        orderDetailBo.setOrderGoods(marketOrderGoods);


        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria userCriteria = marketUserExample.createCriteria();
        userCriteria.andIdEqualTo(marketOrder.getUserId());
        MarketUser marketUser = marketUserMapper.selectOneByExample(marketUserExample);
        orderDetailBo.setUser(marketUser);
        return orderDetailBo;
    }

    @Override
    public List<Express> channel() {
        Express express=new Express("ZTO","中通快递");
        Express express1=new Express("YD","韵达快递");
        Express express2=new Express("YTO","圆通快递");
        Express express3=new Express("EMS","EMS");
        Express express4=new Express("SF","顺丰快递");
        Express express6=new Express("YZPY","邮政快递包裹");
        Express express7=new Express("ZJS","宅急送");
        Express express9=new Express("TNT","TNT快递");
        Express express10=new Express("UPS","UPS");
        Express express5=new Express("DHL","DHL");
        Express express8=new Express("FEDEX","FEDEX(国内件)");
        Express express11=new Express("FEDEX_GJ","FEDEX(国际件)");
        List<Express> expressList=List.of(express,express1,express2,express3,express4,express6,express7,express9,express10,express5,express8,express11);
        return expressList;
    }

    @Override
    public Boolean delete(int orderId) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(marketOrderExample);
        if(marketOrder.getOrderStatus()==102||marketOrder.getOrderStatus()==203){
            marketOrderMapper.deleteByExample(marketOrderExample);
            return true;
        }
        return false;
    }

    @Override
    public Boolean refund(int orderId, int refundMoney) {


        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria marketOrderCriteria = marketOrderExample.createCriteria();
        marketOrderCriteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(marketOrderExample);
        if(marketOrder.getAftersaleStatus()==1){
            //todo 退款金额咋整，优惠券归还
            marketOrder.setOrderStatus((short) 203);
            marketOrder.setAftersaleStatus((short) 3);
            marketOrderMapper.updateByExample(marketOrder,marketOrderExample);
            return true;
        }
        else return false;
    }

    @Override
    public Boolean ship(int orderId, String shipChannel, String shipSn) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria marketOrderCriteria = marketOrderExample.createCriteria();
        marketOrderCriteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(marketOrderExample);
        if(marketOrder.getOrderStatus()==201){
            marketOrder.setShipChannel(shipChannel);
            marketOrder.setShipSn(shipSn);
            marketOrder.setOrderStatus((short) 301);
            marketOrderMapper.updateByExample(marketOrder,marketOrderExample);
            return true;
        }
        else
        return false;
    }

    @Override
    public boolean reply(int commentIdInput, String content) {
        boolean flag=false;
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria = marketCommentExample.createCriteria();
        criteria.andIdEqualTo(commentIdInput);
        MarketComment marketComment = marketCommentMapper.selectOneByExample(marketCommentExample);
        try{
            marketComment.setContent(content);
            marketCommentMapper.updateByExample(marketComment,marketCommentExample);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
            flag=false;
        }finally {
            return flag;
        }

    }

    @Override
    public MarketOrderVo getOrder() {

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(new MarketOrderExample());
        Map<String,List<MarketOrder>> groupByTimeOrders=groupByTime(marketOrders);
        List<MarketOrderVoColumns> rows=new ArrayList<>();
        for (Map.Entry<String, List<MarketOrder>> stringListEntry : groupByTimeOrders.entrySet()) {
            MarketOrderVoColumns row=getRows(stringListEntry.getKey(),stringListEntry.getValue());
            rows.add(row);
        }
        MarketOrderVo data=new MarketOrderVo();
        data.setRows(rows);
        String[] s=new String[]{"day","orders","customers","amount","pcr"};
        data.setColumns(s);
        return data;
    }

    private MarketOrderVoColumns getRows(String key, List<MarketOrder> value) {
        MarketOrderVoColumns r1=new MarketOrderVoColumns();
        r1.setDay(key);
        List<BigDecimal> bigDecimalList=new ArrayList<>();
        Set<Integer> userIdList=new HashSet<>();
        for (MarketOrder marketOrder : value) {
            BigDecimal actualPrice = marketOrder.getActualPrice();
            Integer userId = marketOrder.getUserId();
            bigDecimalList.add(actualPrice);
            userIdList.add(userId);
        }
        int size1 = value.size();
        BigDecimal sum=bigDecimalList.stream().reduce(BigDecimal.ZERO,BigDecimal::add);
        int size = userIdList.size();
        BigDecimal value1 = BigDecimal.valueOf(size);
        BigDecimal divide = sum.divide(value1);
        r1.setOrders(size1);
        r1.setCustomers(size);
        r1.setAmount(sum);
        r1.setPcr(divide);
        return r1;
    }

    private Map<String, List<MarketOrder>> groupByTime(List<MarketOrder> marketOrders) {
        Map<String,List<MarketOrder>> listMap=new TreeMap<>();
        for (MarketOrder marketOrder : marketOrders) {
            LocalDateTime confirmTime = marketOrder.getConfirmTime();

            if(confirmTime!=null){
                String timeCon = TimeConUtil.TimeCon(confirmTime);
                List<MarketOrder> list=listMap.get(timeCon);
                if(list==null){
                    list=new ArrayList<>();
                }
                list.add(marketOrder);
                listMap.put(timeCon,list);
            }
        }

        return listMap;
    }
}
